import {
	createContext,
	useContext,
	useRef,
	useCallback,
	useEffect,
} from 'react'
/* 自动上报pv/click的埋点 */
export const LogContext = createContext(null)
export default function useLog() {
	// 一些公共参数
	const message = useContext(LogContext)
	const listenDOM = useRef(null)

	/* 分清依赖关系 -> message 改变 */
	const reportMessage = useCallback(
		function (data, type) {
			if (type === 'pv') {
				// pv 上报
				console.log('组件 pv 上报', message)
			} else if (type === 'click') {
				// 点击上报
				console.log('组件 click 上报', message, data)
			}
		},
		[message]
	)

	useEffect(() => {
		const handleClick = function (e) {
			reportMessage(e.target, 'click')
		}
		if (listenDOM.current) {
			listenDOM.current.addEventListener('click', handleClick)
		}

		return () => {
			listenDOM.current?.removeEventListener('click', handleClick)
		}
	}, [reportMessage])

	return [listenDOM, reportMessage]
}
